<template>
  <div v-loading="loading" class="s-table-box">
    <el-card :border="false" v-if="localQuerys.length" class="tw-mb-md query-form">
      <form-create :option="queryConfig" :rule="localQuerys" v-model="fapi" @submit="onSubmit"></form-create>
    </el-card>
    <el-card :border="false">
      <slot name="table-top"></slot>
      <el-row>
        <el-button type="primary" round @click="refresh(true)" v-if="hasRefresh">
          <i class="el-icon-refresh"></i>
        </el-button>
        <el-button type="primary" @click="$emit('add')" v-if="addText">
          <i class="el-icon-plus"></i>
          {{ addText }}
        </el-button>
      </el-row>
      <vxe-table :data="dataSource" class="tw-mt-md" highlight-hover-row size="small" stripe v-bind="$attrs" align="center">
        <slot>
          <vxe-table-column v-for="(item, index) in columns" :key="index" v-bind="filterColumnProps(item)">
            <template #default="scope" v-if="item.slotName">
              <slot :name="item.slotName" v-bind="scope"></slot>
            </template>
          </vxe-table-column>
        </slot>
      </vxe-table>
      <vxe-pager v-if="pageConfig.total > 0" v-bind="pageConfig" class="tw-mt-md" @page-change="pageChange" />
    </el-card>
  </div>
</template>

<script>
import { handleApi } from '../util';
import formCreate from '@form-create/element-ui';

const noColumnProps = ['slotName'];
export default {
  components: {
    formCreate: formCreate.$form(),
  },
  data() {
    return {
      loading: false,
      dataSource: [],
      queryConfig: {
        form: {
          inline: true,
          labelWidth: '70px',
        },
        resetBtn: false,
        submitBtn: false,
      },
      fapi: null,
      pageConfig: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        size: 'medium',
        border: true,
      },
    };
  },
  props: {
    hasRefresh: {
      type: Boolean,
      default: true,
    },
    addText: {
      type: String,
      default: '',
    },
    columns: {
      type: Array,
      default: () => [],
    },
    querys: {
      type: Array,
      default: () => [],
    },
    api: [String, Object],
    autoRequest: {
      type: Boolean,
      default: true,
    },
    rowsField: {
      type: String,
      default: 'list',
    },
    totalField: {
      type: String,
      default: 'count',
    },
  },
  computed: {
    localQuerys() {
      const { querys } = this;
      const _querys = querys.map((item) => {
        const _item = {
          ...item,
        };
        return _item;
      });
      if (_querys.length) {
        _querys.push({
          type: 'el-row',
          native: true,
          props: {
            class: 'tw-ml-md',
          },
          children: [
            {
              type: 'ElButton',
              props: {
                type: 'primary',
              },
              on: {
                click: () => {
                  this.clickQuery();
                },
              },
              children: ['查询'],
            },
            {
              type: 'ElButton',
              on: {
                click: () => {
                  this.reset();
                },
              },
              children: ['重置'],
            },
          ],
        });
      }
      return _querys;
    },
  },
  mounted() {
    if (this.autoRequest) {
      this.loadData();
    }
  },
  methods: {
    fapiFn(name, ...args) {
      if (this.fapi) {
        this.fapi[name](...args);
      }
    },
    filterColumnProps(column) {
      const obj = {};
      Object.keys(column).forEach((key) => {
        if (!noColumnProps.includes(key)) {
          obj[key] = column[key];
        }
      });
      return obj;
    },
    loadData() {
      this.loading = true;
      const { currentPage: page, pageSize: limit } = this.pageConfig;
      handleApi(this.api, {
        page,
        limit,
        ...this.getParams(),
      })
        .then(({ data }) => {
          this.dataSource = data[this.rowsField];
          this.$set(this.pageConfig, 'total', data[this.totalField]);
          this.$emit('result', data);
        })
        .catch(() => {
          this.dataSource = []
        })
        .finally(() => {
          setTimeout(() => {
            this.loading = false;
          }, 300);
        });
    },
    pageChange({ type, currentPage, pageSize }) {
      console.log(type, currentPage, pageSize);
      if (type === 'current') {
        this.$set(this.pageConfig, 'currentPage', currentPage);
        this.refresh(false);
      } else if (type === 'size') {
        this.$set(this.pageConfig, 'pageSize', pageSize);
        this.refresh(true);
      }
    },
    getParams() {
      if (this.localQuerys.length) {
        return this.fapi.formData();
      }
      return {};
    },
    refresh(flag = false) {
      if (flag) {
        this.$set(this.pageConfig, 'currentPage', 1);
      }
      this.loadData();
    },
    onSubmit() {
      this.fapi.submit();
    },
    clickQuery() {
      this.refresh(true);
    },
    reset() {
      this.fapi.resetFields();
      this.refresh(true);
    },
  },
};
</script>

<style lang="scss" scoped>
.query-form {
  ::v-deep .el-card__body {
    padding-bottom: unset !important;
  }
}
.s-table-box {
  ::v-deep .vxe-table--render-default .vxe-cell {
      white-space: unset;
      word-break: break-all;
      padding-left: 10px;
      padding-right: 10px;
  }
}
</style>
